<?php

namespace Drupal\jsonapi_cross_bundles\ResourceType;

use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi_extras\ResourceType\ConfigurableResourceType;

/**
 * Resource type that allows collections for all bundles in an entity type.
 */
final class CrossBundlesResourceType extends ConfigurableResourceType {

  /**
   * The resource types that this resource type aggregates.
   *
   * @var \Drupal\jsonapi\ResourceType\ResourceType[]
   */
  protected $bundleResourceTypes;

  /**
   * Sets the cross bundle resource types.
   *
   * @param array $bundle_resource_types
   *   An array of the bundle-specific resource types that this object
   *   aggregates.
   *
   * @return static
   */
  public function setBundleResourceTypes(array $bundle_resource_types) {
    $this->bundleResourceTypes = $bundle_resource_types;
  }

  /**
   * Gets individual JSON:API resource types that this resource type aggregates.
   *
   * @return \Drupal\jsonapi\ResourceType\ResourceType[]
   *   An array of bundle-specific resource types.
   */
  public function getBundleResourceTypes() {
    if (!isset($this->bundleResourceTypes)) {
      throw new \LogicException("setBundleResourceTypes() must be called before getting the bundle resource types.");
    }
    return $this->bundleResourceTypes;
  }

  /**
   * {@inheritdoc}
   */
  public function getPath() {
    if($this->entityTypeId == $this->bundle) {
      $resource_config = $this->getJsonapiResourceConfig();
      if (!$resource_config) {
        return $this->entityTypeId;
      }
    }
    return parent::getPath();
  }

  /**
   * {@inheritdoc}
   */
  public function getBundle() {
    return $this->entityTypeId;
  }

  /**
   * {@inheritdoc}
   */
  // public function isMutable() {
  //   return FALSE;
  // }

}
